package awesomeTask

import (
	"awesomeTask/application/client"
	"awesomeTask/application/variable"
	awesomeTask "awesomeTask/commom"
	"awesomeTask/config"
	"awesomeTask/system/helper"
	"fmt"
	"time"
)

func run() {
}
func Scan() {
	for true {
		if variable.IsMaster == false {
			time.Sleep(10 * time.Second)
			continue
		}
		if len(client.Nodes) == 0 {
			time.Sleep(time.Second * 5)
			fmt.Println("暂无可用的连节点===>等待可用的节点")
			continue
		}
		//return
		task := awesomeTask.Query("select * from t_datasourcetask_back_fill where status=1 and run_time<=?", awesomeTask.Now())
		whereString, whereInParams := awesomeTask.WhereIn(awesomeTask.GetListByKey(task, "task_id"))
		data := awesomeTask.Query(helper.Format("select n.*,t.id as task_id from t_node_back_fill as n INNER join t_datasourcetask_back_fill as t on t.task_id=n.id where n.id in {}", whereString), whereInParams...)
		if len(data) == 0 {
			time.Sleep(10 * time.Second)
			continue
		}
		fmt.Println("当前可用节点数:", len(client.Nodes))
		for _, task := range data {
			node := client.GetBestNode()
			//fmt.Println(task)
			/**
			将任务的状态设置为待执行 防止任务再次被推送
			*/
			if node.PushTask(task) {
				updateMap := make(map[string]interface{})
				updateMap["status"] = 2
				awesomeTask.Update("t_datasourcetask_back_fill", updateMap, "where id=?", task["task_id"])
				eventInfo := map[string]interface{}{
					"source": config.GetConfigByKey("location"),
					"to":     node.Location,
					"descIp": node.IpAddress,
					"taskId": task["task_id"],
				}
				client.SendEventToAll(variable.ON_PUSH_TASK, eventInfo)
			}
		}
	}
}
